<?php /** @noinspection ALL */

//代理管理

namespace app\admin\controller;

use think\facade\Config;
use think\facade\Db;

//include_once 'phpqrcode.php';

class Agent {

	//添加代理需要的数据
	function add_agent_needData() {
		$input=input();

		$userinfo=Pubilc::check_jwt($input['token']);

		if(!$userinfo)return json(['code' => 0,'msg'=>'请重新登录']);

		$id=$userinfo->userId;

		$type=$userinfo->type;

		if($type==2){//代理
			$agentlist = Db::query("select id,level,nick_name from agent where find_in_set('{$id}',team_tag) and level <= 3 ");

		}else{
			$agentlist = Db::table('agent')
				->field('id,level,nick_name')
				->where('level', '<=', 3)
				->select()
				->all();
		}
		array_push($agentlist,['id'=>0,'level'=>'','nick_name'=>'顶级']);

		return json(['code' => 1, 'data' => $agentlist]);
	}

	//提交 添加代理 & 编辑代理
	function add_agent() {
		$input = input();

		if (empty($input['number'])) return json(['code' => 0, 'msg' => '请输入账号']);

		if (empty($input['password'])) return json(['code' => 0, 'msg' => '请输入登录密码']);

		if (empty($input['nick_name'])) return json(['code' => 0, 'msg' => '请输入代理昵称']);

		if (empty($input['real_name'])) return json(['code' => 0, 'msg' => '请输入代理名称']);

		if (empty($input['ratio'])) return json(['code' => 0, 'msg' => '请输入佣金比例']);

		if (empty($input['rebate'])) return json(['code' => 0, 'msg' => '请输入分红比例']);

		if (!is_numeric($input['parentid'])) return json(['code' => 0, 'msg' => '请选择上级代理']);

		if (empty($input['level'])) return json(['code' => 0, 'msg' => '请选择代理等级']);

		if (intval($input['ratio']||intval($input['rebate'])) <= 0) {
			return json(['code' => 0, 'msg' => '比例应大于0']);
		}

		if (intval($input['ratio']||intval($input['rebate'])) > 100) {
			return json(['code' => 0, 'msg' => '比例应小于100']);
		}

		if ($input['parentid'] != 0) {
			$agentinfo = Db::table('agent')->where('id', $input['parentid'])->find();

			if ($agentinfo['level'] != intval($input['level'] - 1)) {
				$level = intval($agentinfo['level'] + 1);
				return json(['code' => 0, 'msg' => "代理等级应选择{$level}级"]);
			}
		} else {
			if ($input['level'] != 1) {
				return json(['code' => 0, 'msg' => '代理等级请选择1级']);
			}
		}

		$is_exists=Db::table('agent')->where('number', $input['number'])->find();

		if(empty($input['id'])){

			$password=md5($input['password']);

			if(!empty($is_exists)) return json(['code' => 0, 'msg' => "该账号已存在"]);

			$number=$input['number'];

		}else{

			$old=Db::table('agent')->find($input['id']);

			if($input['password']==$old['password']){

				$password=$old['password'];
			}else{
				$password=md5($input['password']);
			}

			if($old['number']==$input['number']){

				$number=$old['number'];

			}else{

				if(!empty($is_exists)) return json(['code' => 0, 'msg' => "该账号已存在"]);

				$number=$input['number'];
			}
		}

		$data = [
			'number' => $number,
			'password' => $password,
			'nick_name' => $input['nick_name'],
			'real_name' => $input['real_name'],
			'phone' => $input['phone'],
			'ratio' => $input['ratio'],
			'rebate' => $input['rebate'],
			'status' => $input['status'],
			'add_time' => time(),
			'parentid' => $input['parentid'],
			'level' => $input['level'],
			'arr' => '4,5,6,7,22,23,21,14,15,9,10,11',
			'avatar' => 'https://dss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=3280696440,2906944118&fm=26&gp=0.jpg',
		];

		if(empty($input['id'])){

			$addagentid = Db::table('agent')->insertGetId($data);

			$create_qrcode=self::create_qrcode($addagentid);

			$data['qrcode']=$create_qrcode['qrcodeData'];

			$data['link']=$create_qrcode['link'];

			$re=Db::table('agent')->where('id', $addagentid)->update($data);

			if(!$re||!$addagentid)return json(['code' => 0, 'msg' => '编辑失败']);

		}else{

			$re=Db::table('agent')->where('id', $input['id'])->update($data);

			if(!$re)return json(['code' => 0, 'msg' => '编辑失败']);

		}
		return json(['code' => 1, 'msg' => '编辑成功']);
	}


	//展示所有代理人员
	function show_all_agentList($page=1,$pageSize=10) {

		$input=input();

		$userinfo=Pubilc::check_jwt($input['token']);

		if(!$userinfo)return json(['code' => 0,'msg'=>'请重新登录']);

		$id=$userinfo->userId;

		$type=$userinfo->type;

		if(empty($id))return json(['code' => 0,'msg'=>'用户参数错误']);

		$condition = ' and 1=1';

		if (!empty($input['phone'])) {
			$input['phone']=trim($input['phone']);
			$condition .= " and (nick_name like '%{$input['phone']}%' or phone like '%{$input['phone']}%' or real_name like '%{$input['phone']}%' or number like '%{$input['phone']}%' ) ";
		}

		if (!empty($input['time'])) {
			$start=$input['time'][0]/1000;
			$end=$input['time'][1]/1000;
			$condition .= " and add_time >= $start and add_time <=  $end";
		}

		if($type==2){//代理

			$agentList = Db::query("select * from agent where 1".$condition." and find_in_set('{$id}',team_tag) order by id desc limit ".(($page-1)*$pageSize).",$pageSize");

			$total_num=Db::query("select * from agent where 1".$condition." and find_in_set('{$id}',team_tag) ");

		}else{//管理员

			$agentList = Db::query("select * from agent where 1".$condition." order by id desc limit ".(($page-1)*$pageSize).",$pageSize");

			$total_num=Db::query("select * from agent where 1".$condition);
		}


		for ($i = 0; $i < count($agentList); $i++) {

			$up = Db::table('agent')->field('nick_name')->where('id', $agentList[$i]['parentid'])->find();

			if (!empty($up)) {
				$agentList[$i]['up_agent'] = $up['nick_name'];
			}else{
				$agentList[$i]['up_agent'] = '顶级';
			}
			$agentList[$i]['add_time']=date('Y-m-d H:i:s',$agentList[$i]['add_time']);

			if(!empty($agentList[$i]['last_time'])){
				$agentList[$i]['last_time']=date('Y-m-d H:i:s',$agentList[$i]['last_time']);
			}else{
				$agentList[$i]['last_time']='未登录';
			}
		}

		return json(['code' => 1, 'data' => $agentList,'total_num'=>count($total_num)]);
	}

	//删除代理
	function del_agent() {
		$input = input();

		if (!$input['id']) return json(['code' => 0, 'msg' => '参数错误']);

		$agent = Db::table('agent')->where('id', $input['id'])->find();

		if (empty($agent)) return json(['code' => 0, 'msg' => '数据不存在']);

		$re = Db::name('agent')->where('id', $input['id'])->delete();

		if (!$re) {
			return json(['code' => 0, 'msg' => '删除失败']);
		}
		return json(['code' => 1, 'msg' => '删除成功']);
	}

	//生成代理二维码和链接
	static function create_qrcode($id){

		$system_config=Db::table('system_config')->field('official_website')->find(1);

		$value = $system_config['official_website'].'?id='.$id; //二维码内容

		$errorCorrectionLevel = 'L';//容错级别

		$matrixPointSize = 6;//生成图片大小

		//生成二维码图片
		include_once app()->getRootPath().'/extend/qrcode/phpqrcode.php';

		$QRcode=new \QRcode();

		$file='images/qrcode/'.time().'.png';

		$QRcode::png($value, app()->getRootPath().'/public/'.$file, $errorCorrectionLevel, $matrixPointSize, 2);

		$data['qrcodeData']=$host.$file;

		$data['link']=$value;

		return $data;
	}


}